import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs";
import { prisma } from "@/lib/prisma";
import { PaginationRequest } from "@/types";
import { DEFAULT_PAGE_SIZE } from "@/lib/constants";

// 获取用户的所有知识库
export async function GET(req: NextRequest) {
  try {
    const { userId } = auth();
    const { searchParams } = new URL(req.url);

    // 检查用户认证
    if (!userId) {
      return NextResponse.json(
        { success: false, error: "未授权" },
        { status: 401 }
      );
    }

    // 获取查询参数
    const page = parseInt(searchParams.get("page") || "1");
    const pageSize = parseInt(
      searchParams.get("pageSize") || DEFAULT_PAGE_SIZE.toString()
    );
    const search = searchParams.get("search") || "";

    // 查询条件
    const where = {
      userId,
      name: {
        contains: search,
        mode: "insensitive" as const,
      },
    };

    // 获取总数
    const total = await prisma.knowledgeBase.count({ where });

    // 获取分页数据
    const knowledgeBases = await prisma.knowledgeBase.findMany({
      where,
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * pageSize,
      take: pageSize,
      include: {
        _count: {
          select: { documents: true },
        },
      },
    });

    // 格式化返回结果
    const result = knowledgeBases.map((kb) => ({
      id: kb.id,
      name: kb.name,
      description: kb.description,
      documentsCount: kb._count.documents,
      createdAt: kb.createdAt,
      updatedAt: kb.updatedAt,
    }));

    // 构建分页响应
    return NextResponse.json({
      success: true,
      data: {
        items: result,
        total,
        page,
        pageSize,
        totalPages: Math.ceil(total / pageSize),
      },
    });
  } catch (error) {
    console.error("获取知识库失败:", error);
    return NextResponse.json(
      { success: false, error: "获取知识库失败" },
      { status: 500 }
    );
  }
}

// 创建新知识库
export async function POST(req: NextRequest) {
  try {
    const { userId } = auth();

    // 检查用户认证
    if (!userId) {
      return NextResponse.json(
        { success: false, error: "未授权" },
        { status: 401 }
      );
    }

    const body = await req.json();
    const { name, description } = body;

    // 验证请求数据
    if (!name || typeof name !== "string") {
      return NextResponse.json(
        { success: false, error: "知识库名称是必填项" },
        { status: 400 }
      );
    }

    // 检查用户是否存在
    const user = await prisma.user.findUnique({
      where: { clerkId: userId },
    });

    if (!user) {
      return NextResponse.json(
        { success: false, error: "用户不存在" },
        { status: 404 }
      );
    }

    // 创建知识库
    const knowledgeBase = await prisma.knowledgeBase.create({
      data: {
        name,
        description,
        userId: user.id,
      },
    });

    return NextResponse.json({
      success: true,
      data: knowledgeBase,
    });
  } catch (error) {
    console.error("创建知识库失败:", error);
    return NextResponse.json(
      { success: false, error: "创建知识库失败" },
      { status: 500 }
    );
  }
} 